package mwa.cs.admin.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.*;
import mwa.cs.database.Database;
import mwa.cs.model.*;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class CS89000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private Database db;
	
    public CS89000Srvl() {
        super();
    }

    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

    	// get site_id
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
    	vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());

    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
    	String vaProcessType = request.getParameter("process_type");

    	if(vaProcessType != null && vaProcessType.equals("getDataCustomer")){
			getDataCustomer(request,response);
		}
    	else if(vaProcessType != null && vaProcessType.equals("chkPackageID")){
    		chkPackageID(request,response);
		}
		else if(vaProcessType.equals("getDataTable")){
    		
			getDataTable(request,response);
		}
		else if(vaProcessType.equals("addRole"))
		{
			addRole(request,response);
		}
		else if(vaProcessType.equals("editRole"))
		{
			editRole(request,response);
		}
		else if(vaProcessType.equals("deleteRole"))
		{
			deleteRole(request,response);
		}
    }

    public void getDataCustomer(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	String[] vaMessage = null, vaValue = null;
    	
    	this.db = new Database();
    	
    	SitesDAO voDao = new SitesDAO(db);
		List<Map<String, Object>> voListFindAll = voDao.findAll();
		
		vaValue = new String[voListFindAll.size()];
		vaMessage = new String[voListFindAll.size()];
		
		for (int i = 0; i < voListFindAll.size(); i++) {
			Map<String, Object> voObject = voListFindAll.get(i);
		
			if( voObject.get("PACKAGE_ID") == null ){
				vaValue[i] = "NULL,"+(voObject.get("SITE_ID"));
			}else{
				vaValue[i] = ((String) voObject.get("PACKAGE_ID"))+","+(voObject.get("SITE_ID")); 
			}
			
			vaMessage[i] = (String) voObject.get("SITE_NAME");		
		}

		PrintWriter voOut = response.getWriter();
		try {
			JSONObject voObject = new JSONObject();
			JSONArray voList = new JSONArray();
			if (vaMessage != null) {
				for (int i = 0; i < vaMessage.length; i ++) {
					voList.add(vaMessage[i]);
				}
			}
			voObject.put("messages", voList);
			JSONArray voList2 = new JSONArray();
			if (vaValue != null) {
				for (int i = 0; i < vaValue.length; i ++) {
					voList2.add(vaValue[i]);
				}
			}
			voObject.put("values", voList2);
			
			voOut.print(voObject.toJSONString());
		} finally {
			db.close();
			voOut.close();
		}	
	
    }
    
    public void chkPackageID(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	this.db = new Database();
    	
    	int vaValue = 0;
    	String vaPackageId = request.getParameter("packageID");
    	
    	SMRoleDAO voDao = new SMRoleDAO(db);
    	
    	List<Map<String, Object>> voChkMaping = voDao.checkMapping(vaPackageId);
    	
    	vaValue = voChkMaping.size();
    	
    	PrintWriter voOut = response.getWriter();
    	try {
	    	JSONObject voObject = new JSONObject();
	    	voObject.put("values", vaValue);
	    	
	    	voOut.print(voObject.toJSONString());
	    } finally {
	    	db.close();
			voOut.close();
		}	
    }
    
    public void getDataTable(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		String vaSiteId = request.getParameter("sSearch_0");

		if(vaSiteId.equals("Default")){
			
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			
			voOut.print(voObject.toJSONString());
			return;
		}
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			// return empty
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			voOut.print(voObject.toJSONString());
			return;
		}

		
		SMRoleDAO voDao = new SMRoleDAO(db);
		List<Map<String, Object>> voListFindAll = voDao.findRoleBySiteId(vaSiteId);
		
		if(voListFindAll == null || voListFindAll.size() == 0)
		{
			// return empty
			db.close();
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			voOut.print(voObject.toJSONString());
			return;
		}

		for (int i = 0; i < voListFindAll.size(); i++) 
		{
			Map<String, Object> voMapItem = (Map<String, Object>) voListFindAll.get(i);
			
			voColumn = new JSONArray();
			voColumn.add(i + 1);
			voColumn.add(voMapItem.get("ROLE_ID").toString());
			voColumn.add(voMapItem.get("ROLE_NAME").toString());

			if(voMapItem.get("STATUS").toString().equals("N"))
			{
				voColumn.add("<div><font color='red'><i class='glyphicon glyphicon-remove'></i></font></div><div><font color='red'>ยังไม่ดำเนินการ</font></div>");
			}
			else
			{
				voColumn.add("<div><font color='green'><i class='glyphicon glyphicon-ok'></i></font></div><div><font color='green'>ดำเนินการแล้ว</font></div>");
			}
			voRow.add(voColumn);
		}

		voObject.put("iTotalRecords", voListFindAll.size());
		voObject.put("iTotalDisplayRecords", voListFindAll.size());
		voObject.put("aaData", voRow);
		
		db.close();
		voOut.print(voObject.toJSONString());
		
    }
    
    public void addRole(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		PrintWriter voOut = response.getWriter();
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			voOut.print("connect_db_fail");
			return;
		}
		
		int vnSiteId2 = Integer.parseInt(request.getParameter("siteID").toString());
		String vaRoleId = request.getParameter("roleId").toString();
		String vaRoleName = request.getParameter("roleName").toString();	
		
		JDate voJDate = new JDate();
		String vaDate = voJDate.getDate();
		String vaTime = voJDate.getTime();
		
		SMRole r = new SMRole();
		r.setVaRoleId(vaRoleId);
		r.setVnSiteId(vnSiteId2);
		r.setVaRoleName(vaRoleName);
		r.setVaStatus("N");
		r.setVnInsertUserId(vnUserId);
		r.setVaInsertDate(vaDate);
		r.setVaInsertTime(vaTime);
		r.setVnUpdateUserId(vnUserId);
		r.setVaUpdateDate(vaDate);
		r.setVaUpdateTime(vaTime);
		
		
		SMRoleDAO voDao = new SMRoleDAO(db);
		boolean vbIsDuplicate = voDao.isDuplicate(vaRoleId, vaRoleName);

		if(vbIsDuplicate)
		{
			db.close();
			// Return duplicate
			voOut.print("duplicate");
		}
		else
		{
			try
			{
				voDao.addRole(r);
				voOut.print("success");
			}
			catch(Exception ex)
			{
				voOut.print("fail");
			} finally{
				db.close();
			}
		}
    }
    
    public void editRole(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {	
		PrintWriter voOut = response.getWriter();	
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			voOut.print("connect_db_fail");
			return;
		}
		
		int vnSiteId2 = Integer.parseInt(request.getParameter("siteID").toString());
		String vaRoleId = request.getParameter("roleId").toString();
		String vaRoleName = request.getParameter("roleName").toString();
		int vnOldRoleId = Integer.parseInt(request.getParameter("oldroleId").toString());
		
		SMRoleDAO vaDao = new SMRoleDAO(db);
		
		// เช็ค site_id ที่จะอัพเดทว่ามีอยู่ในระบบหรือไม่
		Map<String, Object> voOldRoleObj = (Map<String, Object>)vaDao.findRoleByRoleId(vnOldRoleId);
		if(voOldRoleObj == null)
		{
			// ไม่มี site_id อยู่ในระบบแล้ว
			db.close();
			voOut.print("no_role");
		}
		else
		{
			JDate voJDate = new JDate();
			String vaDate = voJDate.getDate();
			String vaTime = voJDate.getTime();
			
			SMRole voR = new SMRole();
			voR.setVaRoleId(vaRoleId);
			voR.setVnSiteId(vnSiteId2);
			voR.setVaRoleName(vaRoleName);
			voR.setVaStatus(voOldRoleObj.get("STATUS") == null? null : voOldRoleObj.get("STATUS").toString());
			voR.setVnInsertUserId(voOldRoleObj.get("INSERT_USER_ID") == null? null : Integer.parseInt(voOldRoleObj.get("INSERT_USER_ID").toString()));
			voR.setVaInsertDate(voOldRoleObj.get("INSERT_DATE") == null? null : voOldRoleObj.get("INSERT_DATE").toString());
			voR.setVaInsertTime(voOldRoleObj.get("INSERT_TIME") == null? null : voOldRoleObj.get("INSERT_TIME").toString());
			voR.setVnUpdateUserId(vnUserId);
			voR.setVaUpdateDate(vaDate);
			voR.setVaUpdateTime(vaTime);

			try
			{
				vaDao.updateRoleAllAtributes(vnOldRoleId,voR);
				voOut.print("success");
			}
			catch(Exception ex)
			{
				voOut.print("fail");
			} finally{
				db.close();
			}
			
		}
    }
    
    public void deleteRole(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {		
		PrintWriter voOut = response.getWriter();		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			voOut.print("connect_db_fail");
			return;
		}
		
		int vnRoleId = Integer.parseInt(request.getParameter("roleId").toString());

		SMRoleDAO voDao = new SMRoleDAO(db);
		
		// เช็ค site_id ที่จะอัพเดทว่ามีอยู่ในระบบหรือไม่
		Map<String, Object> voRoleObj = (Map<String, Object>)voDao.findRoleByRoleId(vnRoleId);
		if(voRoleObj == null)
		{
			// ไม่มี site_id อยู่ในระบบแล้ว
			db.close();
			voOut.print("no_role");
		}
		else
		{
			try
			{
				voDao.deleteRole(vnRoleId);
				voOut.print("success");
			}
			catch(Exception ex)
			{
				voOut.print("fail");
			} finally{
				db.close();
			}
		}
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

}
